package com.qingmeng.outsourcing.portal.config;

import com.qingmeng.outsourcing.model.User;
import com.qingmeng.outsourcing.portal.model.PortalUserDetails;
import com.qingmeng.outsourcing.portal.service.UserService;
import com.qingmeng.outsourcing.security.config.SecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@EnableWebSecurity
@Configuration
public class PortalSecurityConfig extends SecurityConfig {

    @Autowired
    private UserService userService;
    /**
     * Allows modifying and accessing the {@link UserDetailsService} from
     * {@link #userDetailsServiceBean()} without interacting with the
     * {@link ApplicationContext}. Developers should override this method when changing
     * the instance of {@link #userDetailsServiceBean()}.
     *
     * @return the {@link UserDetailsService} to use
     */
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                User user = userService.getUserByUsername(username);
                if (user != null) {
                    return new PortalUserDetails(user);
                }
                return null;
            }
        };
    }
}
